#ifndef __COMM_HPP__
#define __COMM_HPP__

#include <iostream>
#include <unistd.h>
#include <string>
#include <sys/types.h>
#include <sys/ipc.h>
#include <string.h>
#include <stdlib.h>
#include <sys/shm.h>

using namespace std;
const char* path  = "/home/yss";
int proj_id =  0x66;
int defaultsize = 4096;

//16进制转换
string ToHex(key_t key)
{
    char buffer[1024];
    snprintf(buffer, sizeof(buffer), "0x%x", key);
    return buffer;
}

//获取key
key_t getkeyOrdie()
{
    key_t k = ftok(path, proj_id);
    if(k < 0)
    {
        cout << "getkey fail, error: " << errno << "stringerror: " << strerror(errno) << endl;
        exit(1);
    }
    return k;
}

//获取shm
int getShmOrdie(key_t key, size_t size, int flag)
{
    int shmid = shmget(key, size, flag);
    if(shmid < 0)
    {
        cout << "getshm fail, error: " << errno << "stringerror: " << strerror(errno) << endl;
        exit(1);
    }
    return shmid;
}

//创建shm
int CreateShm(key_t key, size_t size)
{
    return getShmOrdie(key, size, IPC_CREAT|IPC_EXCL|0666);
}

//得到shm
int GetShm(key_t key, size_t size)
{
    return getShmOrdie(key, size, IPC_CREAT);
}


//删除shm
void DeleteShm(int shmid)
{
    int n = shmctl(shmid, IPC_RMID, nullptr);
    if(n < 0)
    {
        cout << "delete fail" << endl;
    }
    else 
    {
        cout << "delete success" << endl;
    }
}

//挂接shm
void* AttachShm(int shmid)
{
    void* addr = shmat(shmid, nullptr, 0);
    if((long long int)addr == -1)
    {
        cout << "attach fail" << endl;
        return nullptr;
    }
    return addr;
}

//去挂接
void DetachShm(void* addr)
{
    int n = shmdt(addr);
    if(n < 0)
    {
        cout << "detach fail" << endl;
    }
}

#endif